package com.bd.wechat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.bd.wechat.core.exception.ServiceException;
import com.bd.wechat.entity.FranchiseApproveRecord;
import com.bd.wechat.entity.FranchiseFile;
import com.bd.wechat.entity.ShopFranchise;
import com.bd.wechat.entity.request.FranchiseApplyForRequest;
import com.bd.wechat.entity.request.FranchiseApproveRequest;
import com.bd.wechat.entity.request.MyRecordFranchisePageRequest;
import com.bd.wechat.entity.request.ShopFranchisePageRequest;
import com.bd.wechat.entity.response.ShopFranchiseDetailResponse;
import com.bd.wechat.entity.response.ShopFranchiseMyRecordResponse;
import com.bd.wechat.mapper.ShopFranchiseMapper;
import com.bd.wechat.service.FranchiseApproveRecordService;
import com.bd.wechat.service.FranchiseFileService;
import com.bd.wechat.service.ShopFranchiseService;
import com.bd.wechat.utils.JwtTokenUtil;
import com.bd.wechat.utils.SecurityUtils;
import com.bd.wechat.utils.StringUtils;
import com.bd.wechat.utils.UserIdUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.jaxb.SpringDataJaxb;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 店铺加盟 服务实现类
 * </p>
 *
 * @author linhs
 * @since 2024-11-15
 */
@Service
public class ShopFranchiseServiceImpl extends ServiceImpl<ShopFranchiseMapper, ShopFranchise> implements ShopFranchiseService {

    @Resource
    private FranchiseFileService franchiseFileService;
    @Resource
    private FranchiseApproveRecordService franchiseApproveRecordService;

    @Override
    public Page<ShopFranchiseMyRecordResponse> pageMyRecord(Integer pageNum, Integer pageSize, MyRecordFranchisePageRequest pageRequest) {
        Long currentMemberId = UserIdUtil.getCurrentUserId();
        Page<ShopFranchise> shopFranchisePage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ShopFranchise> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShopFranchise::getMemberId, currentMemberId);
        wrapper.orderByDesc(ShopFranchise::getCreateTime);

        Page<ShopFranchiseMyRecordResponse> shopFranchiseMyRecordResponsePage = new Page<>(pageNum, pageSize);
        List<ShopFranchise> shopFranchiseList = this.page(shopFranchisePage, wrapper).getRecords();
        if (CollectionUtils.isEmpty(shopFranchiseList)) {
            return shopFranchiseMyRecordResponsePage;
        }

        List<ShopFranchiseMyRecordResponse> dataList = new ArrayList<>();
        for (ShopFranchise shopFranchise : shopFranchiseList) {
            ShopFranchiseMyRecordResponse shopFranchiseMyRecordResponse = new ShopFranchiseMyRecordResponse();
            BeanUtils.copyProperties(shopFranchise, shopFranchiseMyRecordResponse);

            List<FranchiseFile> franchiseFileList = franchiseFileService.list(new LambdaQueryWrapper<FranchiseFile>().eq(FranchiseFile::getFranchiseId, shopFranchise.getId()));

            //门头照片
            List<FranchiseFile> doorPhoto = franchiseFileList.stream()
                    .filter(e -> e.getType().equals(FranchiseFile.DOOR_PHOTO_TYPE)).collect(Collectors.toList());

            //周边环境照片及热力图
            List<FranchiseFile> envHeatMapPhoto = franchiseFileList.stream()
                    .filter(e -> e.getType().equals(FranchiseFile.ENV_HEAT_MAP_PHOTO_TYPE)).collect(Collectors.toList());

            //户型图
            List<FranchiseFile> houseTypePhoto = franchiseFileList.stream()
                    .filter(e -> e.getType().equals(FranchiseFile.HOUSE_TYPE_PHOTO_TYPE)).collect(Collectors.toList());

            //店铺内部环境视频
            List<FranchiseFile> shopInnerVideo = franchiseFileList.stream()
                    .filter(e -> e.getType().equals(FranchiseFile.SHOP_INNER_VIDEO_TYPE)).collect(Collectors.toList());

            shopFranchiseMyRecordResponse.setDoorPhoto(doorPhoto);
            shopFranchiseMyRecordResponse.setEnvHeatMapPhoto(envHeatMapPhoto);
            shopFranchiseMyRecordResponse.setHouseTypePhoto(houseTypePhoto);
            shopFranchiseMyRecordResponse.setShopInnerVideo(shopInnerVideo);


            dataList.add(shopFranchiseMyRecordResponse);

        }

        shopFranchiseMyRecordResponsePage.setRecords(dataList);

        return shopFranchiseMyRecordResponsePage;
    }

    @Override
    public Page<ShopFranchise> pageShopFranchise(Integer pageNum, Integer pageSize, ShopFranchisePageRequest pageRequest) {
        Page<ShopFranchise> shopFranchisePage = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<ShopFranchise> wrapper = new LambdaQueryWrapper<>();
        if (pageRequest != null) {
            wrapper.eq(StringUtils.isNotEmpty(pageRequest.getPhone()), ShopFranchise::getMemberPhone, pageRequest.getPhone());
        }

        Page<ShopFranchise> page = page(shopFranchisePage, wrapper);
        return page;
    }


    @Override
    public ShopFranchiseDetailResponse detail(Long franchiseId) {
        ShopFranchiseDetailResponse detail = new ShopFranchiseDetailResponse();
        ShopFranchise shopFranchise = this.getById(franchiseId);
        if (shopFranchise == null) {
            throw new ServiceException("申请信息未查询到");
        }

        BeanUtils.copyProperties(shopFranchise, detail);

        List<FranchiseFile> franchiseFileList = franchiseFileService.list(new LambdaQueryWrapper<FranchiseFile>().eq(FranchiseFile::getFranchiseId, franchiseId));
        if (!CollectionUtils.isEmpty(franchiseFileList)) {
            List<FranchiseFile> doorPhoto = franchiseFileList.stream().filter(e -> e.getType().equals(FranchiseFile.DOOR_PHOTO_TYPE)).collect(Collectors.toList());
            List<FranchiseFile> envHeatMapPhoto = franchiseFileList.stream().filter(e -> e.getType().equals(FranchiseFile.ENV_HEAT_MAP_PHOTO_TYPE)).collect(Collectors.toList());
            List<FranchiseFile> shopInnerVideo = franchiseFileList.stream().filter(e -> e.getType().equals(FranchiseFile.SHOP_INNER_VIDEO_TYPE)).collect(Collectors.toList());
            List<FranchiseFile> houseTypePhoto = franchiseFileList.stream().filter(e -> e.getType().equals(FranchiseFile.HOUSE_TYPE_PHOTO_TYPE)).collect(Collectors.toList());

            detail.setDoorPhoto(doorPhoto);
            detail.setEnvHeatMapPhoto(envHeatMapPhoto);
            detail.setShopInnerVideo(shopInnerVideo);
            detail.setHouseTypePhoto(houseTypePhoto);
        }


        return detail;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void applyFor(FranchiseApplyForRequest applyForRequest) {

        Long currentMemberId = UserIdUtil.getCurrentUserId();

        ShopFranchise shopFranchise = new ShopFranchise();
        BeanUtils.copyProperties(applyForRequest, shopFranchise);
        shopFranchise.setMemberId(currentMemberId);
        shopFranchise.setCreateTime(LocalDateTime.now());
        boolean save = save(shopFranchise);
        if (save) {

            //门头照片
            if (!CollectionUtils.isEmpty(applyForRequest.getDoorPhoto())) {
                for (String doorPhoto : applyForRequest.getDoorPhoto()) {
                    List<FranchiseFile> list = new ArrayList<>();
                    FranchiseFile franchiseFile = new FranchiseFile();
                    franchiseFile.setFranchiseId(shopFranchise.getId());
                    franchiseFile.setType(FranchiseFile.DOOR_PHOTO_TYPE);//门头照片（四周）
                    franchiseFile.setObjectName(doorPhoto);
                    list.add(franchiseFile);

                    franchiseFileService.saveBatch(list);
                }
            }
            //周边环境照片及热力图
            if (!CollectionUtils.isEmpty(applyForRequest.getEnvHeatMapPhoto())) {
                for (String envHeatMapPhoto : applyForRequest.getEnvHeatMapPhoto()) {

                    List<FranchiseFile> list = new ArrayList<>();
                    FranchiseFile franchiseVideo = new FranchiseFile();
                    franchiseVideo.setFranchiseId(shopFranchise.getId());
                    franchiseVideo.setType(FranchiseFile.ENV_HEAT_MAP_PHOTO_TYPE);
                    franchiseVideo.setObjectName(envHeatMapPhoto);

                    list.add(franchiseVideo);

                    franchiseFileService.saveBatch(list);
                }
            }

            //户型图
            if (!CollectionUtils.isEmpty(applyForRequest.getHouseTypePhoto())) {
                for (String houseTypePhoto : applyForRequest.getHouseTypePhoto()) {

                    List<FranchiseFile> list = new ArrayList<>();
                    FranchiseFile franchiseFile = new FranchiseFile();
                    franchiseFile.setFranchiseId(shopFranchise.getId());
                    franchiseFile.setType(FranchiseFile.HOUSE_TYPE_PHOTO_TYPE);
                    franchiseFile.setObjectName(houseTypePhoto);

                    list.add(franchiseFile);

                    franchiseFileService.saveBatch(list);
                }
            }

            //店铺内部环境视频
            if (!CollectionUtils.isEmpty(applyForRequest.getShopInnerVideo())) {
                for (String shopInnerVideo : applyForRequest.getShopInnerVideo()) {

                    List<FranchiseFile> list = new ArrayList<>();
                    FranchiseFile franchiseFile = new FranchiseFile();
                    franchiseFile.setFranchiseId(shopFranchise.getId());
                    franchiseFile.setType(FranchiseFile.SHOP_INNER_VIDEO_TYPE);
                    franchiseFile.setObjectName(shopInnerVideo);

                    list.add(franchiseFile);

                    franchiseFileService.saveBatch(list);
                }
            }
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approve(FranchiseApproveRequest request) {
        //0-未审批,1-审批通过,2-未通过
        if (request.getApproveStatus().equals("2") && StringUtils.isEmpty(request.getRejectNote())) {
            throw new ServiceException("拒绝原因不能为空");
        }


        ShopFranchise shopFranchise = this.getById(request.getShopFranchiseId());
        if (shopFranchise == null) {
            throw new ServiceException("未查到对应的加盟申请信息");
        }

        if (shopFranchise.getApproveStatus() == 1) {
            throw new ServiceException("审批已通过，无需再次审批");
        }

        ShopFranchise upd = new ShopFranchise();
        upd.setId(shopFranchise.getId());
        upd.setApproveStatus(request.getApproveStatus());
        upd.setUpdateTime(LocalDateTime.now());
        upd.setCurrentApproveUserId(SecurityUtils.getUserId());
        upd.setCurrentApproveUserName(SecurityUtils.getUsername());
        upd.setCurrentApproveTime(LocalDateTime.now());
        if (request.getApproveStatus().equals(1)) {//审批通过
            upd.setRejectNote("");
        } else {
            upd.setRejectNote(request.getRejectNote());
        }

        boolean b = this.updateById(upd);

        if (b) {
            FranchiseApproveRecord franchiseApproveRecord = new FranchiseApproveRecord();
            franchiseApproveRecord.setSysUserId(SecurityUtils.getUserId());
            franchiseApproveRecord.setSysUserName(SecurityUtils.getUsername());
            franchiseApproveRecord.setShopFranchiseId(request.getShopFranchiseId());
            franchiseApproveRecord.setApproveStatus(request.getApproveStatus());
            franchiseApproveRecord.setRejectNote(request.getRejectNote());
            franchiseApproveRecord.setCreateTime(LocalDateTime.now());
            franchiseApproveRecordService.save(franchiseApproveRecord);
        }
    }
}
